package c6;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.LockSupport;

public class LockSupportTest6 {
    private final AtomicBoolean locked = new AtomicBoolean(false);
    private final Queue<Thread> waiters = new ConcurrentLinkedQueue<>();

    public void lock() {
        boolean wasInterrupt = false;
        Thread current = Thread.currentThread();
        waiters.add(current);
        //只有队首的线程可以获取锁
        while (waiters.peek() != current || !locked.compareAndSet(false, true)) {
            LockSupport.park(this);
            if (Thread.interrupted()) {
                wasInterrupt = true;
            }
            waiters.remove();
            if (wasInterrupt) {
                current.interrupt();
            }
        }
    }

    public void unlock() {
        locked.set(false);
        LockSupport.unpark(waiters.peek());
    }

    public static void main(String[] args) throws InterruptedException {
        LockSupportTest6 test6 = new LockSupportTest6();
        test6.waiters.add(new Thread());
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("thread begin lock");
                test6.lock();
                System.out.println("thread end lock");
            }
        });

        thread.start();
        Thread.sleep(1000);
        test6.unlock();
        System.out.println("end");

    }
}
